const express = require("express");
const { ResponseBody } = require("../type");
const { getDatabase, getJsonBySheet, writeDataBase } = require("../database");
const { easyClassConstructor } = require("../util");

const convertMap = {
    name: "名字",
    grade: "等级",
    effect: "效果",
};

class Pellent {
    constructor(parmas) {
        this.id = parmas.id;
        easyClassConstructor(this, parmas, convertMap);
    }
}

const router = express.Router();

router.get("/get", (req, res) => {
    getDatabase()
        .then((data) => {
            const sheet = data.Sheets["丹药"];
            const source = getJsonBySheet(sheet);
            res.json(new ResponseBody(source.map((item) => new Pellent(item))));
        })
        .catch((err) => {
            res.json(new ResponseBody([], 400, "丹药请求错误" + err));
        });
});

router.post("/save", (req, res) => {
    const reqBody = req.body;
    let uid = Math.max(...reqBody.map((item) => item.id ?? -Infinity));
    const data = reqBody.map((item) => {
        const t = Object.entries(item).map((o) => [
            convertMap[o[0]] ?? o[0],
            o[1],
        ]);
        if (!("id" in item)) {
            t.unshift(["id", ++uid]);
        }
        return Object.fromEntries(t);
    });
    writeDataBase("丹药", data)
        .then(() => {
            res.send(new ResponseBody());
        })
        .catch((err) => {
            res.json(new ResponseBody([], 400, "丹药保存错误" + err));
        });
});

module.exports = router;
